package com.white.mysoundrecorder;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewTreeObserver;

/**
 * Created by ytf on 2017/4/10 010.
 * Description:     基础view的封装，实现了测量
 */

public abstract class AbsView extends View implements ViewTreeObserver.OnGlobalLayoutListener
{
    public Context mContext;

    public AbsView(Context context)
    {
        super(context);
        mContext = getContext();
    }

    public AbsView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        mContext = getContext();
    }

    public AbsView(Context context, AttributeSet attrs, int defStyleAttr)
    {
        super(context, attrs, defStyleAttr);
        mContext = getContext();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        setMeasuredDimension(measureWidth(widthMeasureSpec), measureHeight(heightMeasureSpec));
    }

    private int measureWidth(int widthMeasureSpec)
    {
        int result = 0;
        // 获取参数中的测量模式和测量大小
        int specMode = MeasureSpec.getMode(widthMeasureSpec);
        int specSize = MeasureSpec.getSize(widthMeasureSpec);

        if (specMode == MeasureSpec.EXACTLY) {
            // 精确模式，没的说，大小该是多少就是多少
            result = specSize;
        }else{
            result = getDefaultWrapWidth();
            // wrap_content 的话，根据刚才的需求，大小只能是 200 和 specSize 的最小值
            if (specMode == MeasureSpec.AT_MOST) {
                result = Math.min(result, specSize);
            }
        }

        // 注意返回值单位是 px，不是 dp
        return result;
    }

    public abstract int getDefaultWrapWidth();

    private int measureHeight(int heightMeasureSpec)
    {
        int result = 0;
        // 获取参数中的测量模式和测量大小
        int specMode = MeasureSpec.getMode(heightMeasureSpec);
        int specSize = MeasureSpec.getSize(heightMeasureSpec);

        if (specMode == MeasureSpec.EXACTLY)
        {
            result = specSize;
        } else
        {
            result = getDefaultWrapHeight();
            if (specMode == MeasureSpec.AT_MOST)
            {
                result = Math.min(result, specSize);
            }
        }

        // 注意返回值单位是 px，不是 dp
        return result;
    }

    public abstract int getDefaultWrapHeight();

    @Override
    protected void onAttachedToWindow()
    {
        super.onAttachedToWindow();
        getViewTreeObserver().addOnGlobalLayoutListener(this);
    }

    @Override
    protected void onDetachedFromWindow()
    {
        getViewTreeObserver().removeGlobalOnLayoutListener(this);
        super.onDetachedFromWindow();
    }

    public boolean isLayout;

    @Override
    public abstract void onGlobalLayout();


}
